import java.util.Arrays;

public class t1562_2 {
    public static void main(String[] args) {
        int arr[] = {3, 5, 1, 2, 4};
        int m = 1;
        int num = findLatestStep(arr, m);
        System.out.println(num);
    }

    public static int findLatestStep(int[] arr, int m) {
        int cnt = 0;
        int link[] = new int[arr.length];
        int res = -1;
        Arrays.fill(link,-1);
        for(int i = 0;i<arr.length;i++){
            int pos = arr[i] -1;
            link[pos] = pos;
            int L = pos, R = pos;
            if(0<pos && link[pos-1]!=-1){
                if(pos-1 - link[pos-1] +1 ==m){
                    cnt--;
                }
                L = link[pos-1];
            }
            if(pos+1 < arr.length && link[pos+1] != -1){
                if(link[pos+1] - (pos+1) +1 ==m){
                    cnt--;
                }
                R = link[pos+1];
            }
            link[L] = R;
            link[R] = L;
            if(R-L+1 == m){
                cnt++;
            }
            if(cnt>0){
                res = i+1;
            }
        }
        return res;

    }

}
